﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Services.Interface;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
using Newtonsoft.Json.Linq;
using System.Text.Json.Nodes;
using RndMaterialDisposalService.Models.RequestModel;
using Microsoft.AspNetCore.Authorization;
using RndMaterialDisposalService.Models.Entitys;
using RndMaterialDisposalService.Repository;
using RndMaterialDisposalService.Services;
using RndMaterialDisposal.Extensions.Authorization;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;

namespace RndMaterialDisposalService.Controllers
{
    /// <summary>
    /// 自定义授权练习
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AuthTestController : ControllerBase
    {
        private readonly ILogger<AuthTestController> logger;
        private readonly IDataDictionaryService dictService;
        private readonly IPortalCommonService portalCommonService;
        private readonly IUserInfoService userInfoService;
        private readonly ITokenService tokenService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_logger"></param>
        /// <param name="_dictService"></param>
        /// <param name="_IPortalCommonService"></param>
        public AuthTestController(ILogger<AuthTestController> _logger, IDataDictionaryService _dictService, 
            IPortalCommonService _IPortalCommonService, IUserInfoService _IUserInfoService, ITokenService _tokenService)
        {
            logger = _logger;
            dictService = _dictService;
            portalCommonService = _IPortalCommonService;
            userInfoService = _IUserInfoService;
            tokenService = _tokenService;
        }

        /// <summary>
        /// 获取待办列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="keyWord"></param>
        /// <param name="sortField"></param>
        /// <param name="SortDir"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetTodoList")]
        [PageList]
        [Authorize("policy1")]
        public async Task<IActionResult> GetTodoList(string userId, string? keyWord, string? sortField = "ArrivalDate", string? SortDir = "desc", int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var result = await portalCommonService.GetTodoList(userId, keyWord, sortField, SortDir, pageIndex, pageSize);
                var totalCount = result.TotalCount;
                var userResult = ApiResponsePageList<ToDoModel>.CreatePageListByResult(result.Data, pageIndex, pageSize, totalCount);
                return Ok(userResult);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"获取待办列表(移动端),用户ID：{userId},搜索：{keyWord},时间：{DateTime.Now},异常原因：{ex.ToString()}");
                throw;
            }
        }

        /// <summary>
        /// 获取已办列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="keyWord"></param>
        /// <param name="sortField"></param>
        /// <param name="SortDir"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetDoneList")]
        [PageList]
        [Authorize("policy1")]
        public async Task<IActionResult> GetDoneList(string userId, string? keyWord, string? sortField = "ArrivalDate", string? SortDir = "desc", int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var result = await portalCommonService.GetDoneList(userId, keyWord, sortField, SortDir, pageIndex, pageSize);
                var totalCount = result.TotalCount;
                var userResult = ApiResponsePageList<VToDoneDto>.CreatePageListByResult(result.Data, pageIndex, pageSize, totalCount);
                return Ok(userResult);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"获取已办列表(移动端),用户ID：{userId},搜索：{keyWord},时间：{DateTime.Now},异常原因：{ex.ToString()}");
                throw;
            }
        }

        /// <summary>
        /// 获取待阅
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="keyWord"></param>
        /// <param name="sortField"></param>
        /// <param name="SortDir"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetToReadList")]
        [PageList]
        [Authorize("policy1")]
        public async Task<IActionResult> GetToReadList(string userId, string? keyWord, string? sortField = "ArrivalDate", string? SortDir = "desc", int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var result = await portalCommonService.GetToReadList(userId, keyWord, sortField, SortDir, pageIndex, pageSize);
                var totalCount = result.TotalCount;
                var userResult = ApiResponsePageList<VToReadDto>.CreatePageListByResult(result.Data, pageIndex, pageSize, totalCount);
                return Ok(userResult);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"获取待阅(移动端),用户ID：{userId},搜索：{keyWord},时间：{DateTime.Now},异常原因：{ex.ToString()}");
                throw;
            }
        }




        /// <summary>
        /// 查询用户
        /// </summary>
        /// <returns></returns>
        [HttpGet("UserList")]
        [Authorize(UserPermission.UserList)]
        public async Task<IActionResult> UserList()=> Ok("UserList");

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <returns></returns>
        [HttpGet("UserCreate")]
        [Authorize(Policy=UserPermission.UserCreate)]
        [Authorize(UserPermission.User)]
        public async Task<IActionResult> UserCreate()
        {
            return Ok("UserCreate");
        }

        /// <summary>
        /// 跟新用户
        /// </summary>
        /// <returns></returns>
        [HttpGet("UserUpdate")]
        [Authorize(UserPermission.UserUpdate)]
        public async Task<IActionResult> UserUpdate()
        {
            return Ok("UserUpdate");
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <returns></returns>
        [HttpGet("UserDelete")]
        [Authorize(UserPermission.UserDelete)]
        public async Task<IActionResult> UserDelete()
        {
            return Ok("UserDelete");
        }

        /// <summary>
        /// test
        /// 如果只要有效Token就行，不需要校验策略只用Authorize就行。一般适用通用的api,不需要根据角色分权限，仅登录就行访问。
        /// </summary>
        /// <returns></returns>
        [HttpGet("Test")]
        [Authorize]
        public async Task<IActionResult> Test()
        {
             var userName= User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);
            return Ok($"Test方法：我是,{userName?.Value}");
        }

        /// <summary>
        /// 解析token
        /// </summary>
        /// <returns></returns>
        [HttpGet("DecodeJwtToken")]
        [Authorize]
        public async Task<IActionResult> DecodeJwtToken()
        {
            string authHeader = this.HttpContext.Request.Headers["Authorization"];
            string tokenStr = authHeader.Replace("Bearer ", "");
            var handler = new JwtSecurityTokenHandler();
            var payload = handler.ReadJwtToken(tokenStr).Payload;
            var claims = payload.Claims;
            var userName = claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);

            return Ok($"Test方法：我是,{userName?.Value}");
        }

        /// <summary>
        /// 校验token
        /// </summary>
        /// <returns></returns>
        [HttpGet("VerifyJwtToken")]
        [Authorize]
        public async Task<IActionResult> VerifyJwtToken()
        {
            string authHeader = this.HttpContext.Request.Headers["Authorization"];
            string tokenStr = authHeader.Replace("Bearer ", "");
            bool success = await tokenService.VerifyJwtToken(tokenStr);

            return Ok($"token是否有效,{success}");
        }




    }
}
